package generic.queue;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EventConsumer<T> extends Thread {

	public boolean run = false;
	//BlockingQueue<IEvent<T>> consumerQueue;
	//BlockingQueue<IEvent<T>> producerQueue;
	private ExecutorService exec = Executors.newFixedThreadPool(Runtime
			.getRuntime().availableProcessors());

	//private  Map<String, IHandler<T>> handlers;

	private EventQueue<T> queue;
	
	public EventConsumer(EventQueue<T> queue) {
//		this.consumerQueue = consumerQueue;
//		this.producerQueue=producerQueue;
//		this.handlers = handlers;
		this.queue=queue;
	}

	@Override
	public void run() {
		while (!run) {
			IEvent<T> event;

			try {
				while ((event = queue.getConsumerQueue().take()) != null && !run) {
					IHandler<T> handler = queue.getHandlers().get(event.getName());//.newInstance();
					synchronized (event) {
						handler=handler.clone();
						handler.setQueue(queue);						
						handler.setEvent(event);
						exec.execute(handler);	
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 

		}
	}

	public void shutdown() {
		run = true;
		exec.shutdown();
	}

}
